package mx.com.sinformex.chat.core;

import java.util.Iterator;
import java.util.Map;

import mx.com.sinformex.chat.core.server.IChatServer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;

/**
 * @author Oscar Ivan Hernandez Ventura [ oscar at sinformex dot com dot mx]
 *
 * @version $ Id : Manager.java , v 1.0 Aug 12, 2009 angellore $
 * @param <IChatServer>
 */
public class Manager {

	private ApplicationContext ctx;
	private Map<String, IChatServer> servers;
	private final Log log = LogFactory.getLog(getClass());

	public Manager(ApplicationContext ctx) {
		this.ctx = ctx;
	}

	/**
	 * Loads and init servers. If you want to load servers from XML or DB, may be you want to 
	 * overwrite this method.
	 */
	@SuppressWarnings("unchecked")
	public void init() {
		servers = ctx.getBeansOfType(IChatServer.class);

		log.info(String.format("Loaded %d servers", servers.size()));

		for(Iterator<String> iter = servers.keySet().iterator() ; iter.hasNext() ; ) {
			String serverName = iter.next();
			IChatServer server = servers.get(serverName);
			server.setManager(this);

			log.info(String.format("Starting server %s", serverName));
			server.start();
			new Thread(server).start();
		}		
	}

}
